#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import os
import web
import json
import traceback

from sqlalchemy.orm.exc import NoResultFound
from Umpweb.base import render_jinja
from Umpweb.db import api as db_api
from Umpweb.common import utils
from Umpweb.common.utils import login_required

from Umpweb.base import session, _, render_jinja

render = render_jinja('static/templates/cgsnapshot', encoding='utf-8',)


class CGSnapshotList:
    def GET(self):
        web.header("Content-Type", "text/plain")
        return render.cgsnapshot_list()

class CGSnapshotCreate:
    @login_required
    def GET(self):
        x = web.input()
        vgroup_id = x.get('vgroup_id')
        vgroup = db_api.vgroup_get(vgroup_id)
        return render.cgsnapshot_create(vgroup=vgroup)

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = dict(**web.input())

        # values = {
        #     'cgsnapshot_name':x.cgsnapshot_name.strip(),
        #     'vgroup_id':x.vgroup_id,
        #     'username':x.
        # }

        body = {"CGSnapshotCreate":{'params':values}}
        return utils.web_return(body)

class CGSnapshotDelete:

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        body = {"CGSnapshotDelete":{'params':{'id':x.get('id').strip()}}}
        return utils.web_return(body)
        
class CGSnapshotUpdate:

    @login_required
    def GET(self):
        x = web.input()
        cgsnapshot = db_api.cgsnapshot_get(x.get('id'))
        return render.cgsnapshot_update(cgsnapshot=cgsnapshot)

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = {
            'id': x.get('id').strip(),
            'name':x.name.strip(),
           }

        body = {"CGSnapshotUpdate": {'params': values}}
        return utils.web_return(body)


class CGSnapshotRollback:

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = {
            'id': x.get('id').strip(),
           }

        body = {"CGSnapshotRollback": {'params': values}}
        return utils.web_return(body)

class CGSnapshotClone:

    @login_required
    def GET(self):
        x = web.input()
        cgsnapshot = db_api.cgsnapshot_get(x.get('id'))
        return render.cgsnapshot_clone(cgsnapshot=cgsnapshot)

    def POST(self):
        x = web.input()
        web.header("Content-Type", "application/json")
        values = {
            'id': x.get('id').strip(),
            'name':x.name.strip(),
           }

        body = {"CGSnapshotClone": {'params': values}}
        return utils.web_return(body)

class GridCGSnapshot:
    def POST(self):
        web_input = web.input()
        filters = {}
        page, total, records, rows = \
                utils.grid_rows_query(db_api.cgsnapshot_table, web_input, filters=filters)

        for cgsnapshot in rows:
            vgroup = db_api.vgroup_get(cgsnapshot.vgroup_id) 
            if vgroup:
                cgsnapshot.CGSnapshot = vgroup.name
                cgsnapshot.username = vgroup.username

        cells = ['id', 'name', 'CGSnapshot','username','created_at']

        rows_json = utils.grid_json(
                page, total, records, rows, 'id', cells)
        web.header("Content-Type", "application/json")
        return rows_json

class GetCGSnapshots:

    def GET(self):
        x = web.input()
        web.header("Content-Type", "application/json")
        cgsnapshots = db_api.cgsnapshot_get_with_volume(x.volume_id)
        cgsnapshots = [cgsnapshot.__dict__ for cgsnapshot in cgsnapshots]
        return json.dumps(cgsnapshots)

class GridCGSnapshotPolicy:
    def POST(self):
        web_input = web.input()
        filters = {}
        page, total, records, rows = \
                utils.grid_rows_query(db_api.cgsnapshot_policy_table, web_input, filters=filters)


        cells = ['id', 'name', 'username','created_at','operation']

        rows_json = utils.grid_json(
                page, total, records, rows, 'id', cells)
        web.header("Content-Type", "application/json")
        return rows_json

class CGSnapshotPolicyList:
    def GET(self):
        return render.cgsnapshot_policy_list()

class CGSnapshotTask:

    def GET(self):
        x = web.input()
        volume_id = x.get('volume_id')
        volume = db_api.volume_get(volume_id)
        count = unit = ''
        if volume.cgsnapshot_time:
            count_unit = volume.cgsnapshot_time.split('-')[0]
            count = count_unit[:-1]
            unit = count_unit[-1]
        volume.cgsnapshot_cycle = None
        if unit == 'd' :
            volume.cgsnapshot_cycle = "%s天" % count
        if unit == 'm' :
            volume.cgsnapshot_cycle = "%s分钟" % count
        if unit == 'h' :
            volume.cgsnapshot_cycle = "%s小时" % count
        return render.cgsnapshot_task(volume=volume)

    def POST(self):
        x = web.input()
        web.header("Content-Type", "application/json")
        values = {
            'count':x.count.strip(),
            'unit': x.get('unit').strip(),
            'volume_id':x.volume_id,
           }

        body = {"CGSnapshotTask": {'params': values}}
        return utils.web_return(body)


class CGSnapshotPolicyCreate:

    def GET(self):
        return render.cgsnapshot_policy_create()

    def POST(self):
        x = web.input()
        web.header("Content-Type", "application/json")
        values = {
            'count':x.count.strip(),
            'unit': x.get('unit').strip(),
            'name':x.get('name')
           }

        body = {"CGSnapshotPolicyCreate": {'params': values}}
        return utils.web_return(body)


class CGSnapshotPolicyDelete:

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        body = {"CGSnapshotPolicyDelete":{'params':{'id':x.get('id').strip()}}}
        return utils.web_return(body)

class CGSnapshotConsistency:
    def GET(self):
        return render.cgsnapshot_consistency()
